package com.smart.manager.system.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.common.entities.option.SelectOption;
import com.smart.manager.system.entities.body.RSystemPosition;
import com.smart.manager.system.entities.models.SystemPosition;
import com.smart.manager.system.entities.models.query.QSystemPosition;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class PositionRepository {

    public Page<SystemPosition> pageList(RSystemPosition.SearchBody search) {
        QSystemPosition query = new QSystemPosition();
        Opt.ofBlankAble(search.getCode()).ifPresent(x -> query.code.contains(x));
        Opt.ofBlankAble(search.getName()).ifPresent(x -> query.name.contains(x));
        query.order().id.desc();
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<SystemPosition>().load(query.findPagedList());
    }

    public void add(RSystemPosition.EditBody body) {
        QSystemPosition query = new QSystemPosition();
        SystemPosition record = query.code.eq(body.getCode()).setMaxRows(1).findOne();
        Assert.isNull(record, "创建失败:, 职务代码已存在");
        BeanUtil.copyProperties(body, SystemPosition.class)
                .save();


    }


    public void update(Long id, RSystemPosition.EditBody body) {
        QSystemPosition query = new QSystemPosition();
        SystemPosition record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();


    }

    public int delByIds(List<Long> ids) {
        List<SystemPosition> list = new QSystemPosition().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        for (SystemPosition module : list) {
            log.warn("检查数据是否允许被删除  {}", module);
        }
        return DB.deleteAll(list);


    }


    /**
     * 获取数据字典下拉选项
     *
     * @return {@code List<SelectOption>}
     */
    public List<SelectOption> getOptions() {
        return new QSystemPosition().findStream()
                .map(x -> new SelectOption().setLabel(x.getName()).setValue(x.getCode()).setDisabled(false))
                .collect(Collectors.toList());
    }
}
